package xyz.haijin.shiro.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import xyz.haijin.shiro.dao.MenuDAO;
import xyz.haijin.shiro.entity.Menu;
import xyz.haijin.shiro.entity.MenuPermission;
import xyz.haijin.shiro.service.MenuService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDAO menuDAO;

    @Override
    public List<Menu> getUserMenu(Integer userId) {
        List<Menu> menus = menuDAO.getUserMenu(userId);
        return makeMenu(menus);
    }

    @Override
    public List<Menu> getTreeMenu() {
        List<Menu> menus = menuDAO.getAllMenu();
        return makeMenu(menus);
    }

    private List<Menu> makeMenu(List<Menu> menus) {
        Map<Integer, Menu> menuMap = new HashMap<>(menus.size());
        List<Menu> parentMenu = new ArrayList<>();
        for (Menu menu : menus) {
            menuMap.put(menu.getId(), menu);
            if (menu.getParentId() == null) {
                parentMenu.add(menu);
            }
        }
        for (Menu menu : menus) {
            if (menu.getParentId() != null) {
                Menu parent = menuMap.get(menu.getParentId());
                if (parent != null) {
                    parent.getChildren().add(menu);
                }
            }
        }
        return parentMenu;
    }

    @Override
    public List<MenuPermission> getMenuPerms() {
        return menuDAO.getMenuPerms();
    }
}
